package com.shushan.mixedexam;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.home.bean.RewardTimeBean;
import com.shushan.home.bean.RewardToyBean;
import com.shushan.mixedexam.adapter.ExamFragmentAdapter;
import com.shushan.mixedexam.bean.ExerciseBean;
import com.shushan.mixedexam.bean.ExerciseOptionBean;
import com.shushan.mixedexam.bean.ExerciseResultBean;
import com.shushan.mixedexam.bean.PaperBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.ImageUtils;
import com.shushan.util.Session;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName: ExamActivity
 * @Desciption: 考试界面
 * @author: yichaohua
 * @date: 2018-01-04
 */
public class ExamActivity extends BaseActivity /*implements ViewPager.OnPageChangeListener, View.OnClickListener, OnAnswerSelectListener */{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    //    private static final String TAG = "ExamActivity";
//
//    private ViewPager viewPager;
//    private ExamFragmentAdapter examFragmentAdapter;
//    private TextView examTimeTextView;
//    private ImageView examButton;
//    private ImageView ivRight, ivWrong;
//    private Button btnNextTopic;
//    private TextView tvTopicTotalNum,tvCurrentNum;
//
//    private int topicTotalNum;//做题时的总题数
//    private int examTime = 0;
//    private static int pageIndex = 0;
//    private int rightNum = 0;
//    private int wrongNum = 0;
//    private int examTimeForWatchTopic = 0;
//    private static int currentTopicIndex = -1;//当前做到第几题
//
//    private int paperId = 0;
//    private PaperBean examPaperBean;
//    private int awardType;//1.奖励时间；2.奖励玩具；3.边学边练
//    private int examType = 1;//1、同步练习 2、智能练习 3、边学边练 4、重点练习 5、难点练习 6、易错练习 7、专项练习
//    private boolean cannotBackstage = false;
//    private int fromResultType;//从成绩结果页面跳转过来的类型；0:重考；1:查看试卷
//    private boolean isWatchWrongTopic;//是否是查看错题
//    private boolean isFromRecord;//是否来自练习记录
//    private RewardToyBean rewardToyBean;
//    private RewardTimeBean rewardTimeBean;
//    private int subjectId;
//    private int videoId;
//    private int specialId;
//
//    private PowerManager.WakeLock wakeLock;
//    private BabyApplication shuShanApplication = BabyApplication.getInstance();
//
//    private SoundPool soundPool;//播放短小音频
//    private int[] soundResIds = {R.raw.right_audio, R.raw.wrong_audio};
//    private HashMap<Integer, Integer> soundIdMap = new HashMap<>();
//    private AnimationDrawable rightAnimation ;
//    private AnimationDrawable wrongAnimation;
//
//    private CustomDialog skipTopicDialog;
//    Handler scrollHandler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//
//            switch (msg.what) {
//                case 0:
//                    viewPager.setCurrentItem(msg.arg1, true);
//                    break;
//                default:
//                    break;
//            }
//        }
//    };
//    private AnsweredReceiver answeredReceiver;
//    private JumpToShouldAnswerIndexReceiver jumpReceiver;
//
//    private boolean doneFinish = false;
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//        ScreenManager.getInstance().setStatusBar(true, this);
//        setContentView(R.layout.exam_activity);
//
//        cannotBackstage = getIntent().getBooleanExtra("cannotBackstage", false);
//        awardType = getIntent().getIntExtra("awardType", 1);
//        fromResultType = getIntent().getIntExtra("fromResultType", -1);
//        isWatchWrongTopic = getIntent().getBooleanExtra("isWatchWrongTopic",false);
//        isFromRecord = getIntent().getBooleanExtra("isFromRecord",false);
//        paperId = getIntent().getIntExtra("paperId", 0);
//        subjectId = getIntent().getIntExtra("subjectId", 0);
//        videoId = getIntent().getIntExtra("videoId", 0);
//        specialId = getIntent().getIntExtra("specialId", 0);
//        examTimeForWatchTopic = getIntent().getIntExtra("examTime",0);
//
//        rewardTimeBean = (RewardTimeBean) Session.getSession().get("rewardTimeBean");
//        rewardToyBean = (RewardToyBean) Session.getSession().get("rewardToyBean");
//        pageIndex = 0;//页面index归零
//        currentTopicIndex = -1;
//
//        initView();
//
//        getExamPaper();
//
//        if(fromResultType != 1) {
//            handler.postDelayed(examTimeRunnable, 1000);
//        }
//
//        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "KeepScreenOn");
//        wakeLock.acquire();
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//
//        Log.i(TAG,"onResume()");
//
//        initAnswerAnimation();
//        shuShanApplication.setExaming(true);
//    }
//
//    private void initAnswerAnimation(){
//        if(ivRight.getDrawable() == null) {
//            ivRight.setImageResource(R.drawable.anim_answer_right);
//        }
//        if(rightAnimation == null){
//            rightAnimation = (AnimationDrawable) ivRight.getDrawable();
//            rightAnimation.setOneShot(true);
//        }
//        if(ivWrong.getDrawable() == null) {
//            ivWrong.setImageResource(R.drawable.anim_answer_wrong);
//        }
//        if(wrongAnimation == null) {
//            wrongAnimation = (AnimationDrawable) ivWrong.getDrawable();
//            wrongAnimation.setOneShot(true);
//        }
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//
//        Log.i(TAG, "cannotBackstage=" + cannotBackstage);
//
//        if (cannotBackstage) {
//            ActivityManager activityManager = (ActivityManager) getApplicationContext()
//                    .getSystemService(Context.ACTIVITY_SERVICE);
//            activityManager.moveTaskToFront(getTaskId(), 0);
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//
//        Log.i(TAG,"onDestroy()");
//
//        //回收imageview图片资源
//        ImageUtils.releaseImageViewResouce(ivRight);
//        ImageUtils.releaseImageViewResouce(ivWrong);
//
//        //回收动画音频对象
//        rightAnimation = null;
//        wrongAnimation = null;
//        soundPool.release();
//        soundPool = null;
//        soundIdMap = null;
//
//        if (wakeLock != null) {
//            wakeLock.release();
//            wakeLock = null;
//        }
//
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(jumpReceiver);
//
//        doneFinish = true;
//        shuShanApplication.setExaming(false);
//    }
//
//    private void initView() {
//        examButton = findViewById(R.id.exam_title_img);
//        examButton.setOnClickListener(this);
//        examTimeTextView = findViewById(R.id.exam_title_tv);
//        viewPager = findViewById(R.id.exam_vp);
//        viewPager.addOnPageChangeListener(this);
//        tvTopicTotalNum = findViewById(R.id.tv_topic_total_num);
//        tvCurrentNum = findViewById(R.id.tv_current_num);
//        tvCurrentNum.setText("("+1);
//        ivRight = findViewById(R.id.iv_right);
//        ivWrong = findViewById(R.id.iv_wrong);
//        btnNextTopic = findViewById(R.id.btn_next_topic);
//        btnNextTopic.setOnClickListener(this);
//
//        if(fromResultType == 1){//查看习题跳过来的
//            btnNextTopic.setEnabled(true);
//            examTimeTextView.setText(StringTools.formatExamTime(examTimeForWatchTopic));
//            if(isWatchWrongTopic){
//                examTimeTextView.setVisibility(View.GONE);
//                tvCurrentNum.setText("我的错题");
//                tvTopicTotalNum.setVisibility(View.GONE);
//            }
//        }
//
//        soundPool = new SoundPool.Builder().setMaxStreams(soundResIds.length).build();
//        soundIdMap.put(0, soundPool.load(this, soundResIds[0], 1));
//        soundIdMap.put(1, soundPool.load(this, soundResIds[1], 1));
//
//        IntentFilter filter = new IntentFilter(Constants.JUMP_TO_SHOULD_ANSWER_TOPIC_ACTION);
//        jumpReceiver = new JumpToShouldAnswerIndexReceiver();
//        LocalBroadcastManager.getInstance(this).registerReceiver(jumpReceiver,filter);
//    }
//
//    @Override
//    protected void onTitleBack() {
//        if (cannotBackstage) {
//            showToast("考试期间不允许退出");
//        } else if (fromResultType != 1){
//            showNoBackWarnDialog();
//        }else {
//            onBackAction();
//        }
//    }
//
//    @Override
//    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//    }
//
//    @Override
//    public void onPageSelected(int position) {
//        if(skipTopicDialog != null && skipTopicDialog.isShowing()){
//            skipTopicDialog.dismiss();
//        }
//        if(fromResultType != 1) {//如果是做题
//            if (position > currentTopicIndex) {
//                btnNextTopic.setEnabled(false);
//            } else {
//                btnNextTopic.setEnabled(true);
//            }
//        }
//        pageIndex = position;
//
//        if(!isWatchWrongTopic) {
//            tvCurrentNum.setText("(" + (position + 1));
//        }
//
//        showCollect();
//    }
//
//    @Override
//    public void onPageScrollStateChanged(int state) {
//
//    }
//
//    Handler handler = new Handler();
//    Runnable examTimeRunnable = new Runnable() {
//        @Override
//        public void run() {
//            if(doneFinish){
//                return;
//            }
//            examTime++;
//            examTimeTextView.setText(StringTools.formatExamTime(examTime));
//            handler.postDelayed(this, 1000);
//        }
//    };
//
//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.exam_title_img:
//                ExamFragment examFragment = (ExamFragment) examFragmentAdapter.getItem(pageIndex);
//                ExerciseBean exerciseBean = examFragment.getExerciseBean();
//
//                if (exerciseBean.child_collect == 1) {
//                    doPostCollect(2);
//                } else {
//                    doPostCollect(1);
//                }
//
//                break;
//            case R.id.btn_next_topic:
//                if(fromResultType != 1){//不是查看习题过来的
//                    Log.i(TAG,"pageIndex + 1 = "+(pageIndex + 1));
//                    if(pageIndex + 1 == topicTotalNum){
//                        if(!Constants.isForEditors) {
//                            postPaperRecord(examPaperBean);
//                            break;
//                        }
//                    }
//                }
//                Message message = scrollHandler.obtainMessage(0);
//                message.arg1 = pageIndex + 1;
//                scrollHandler.sendMessageDelayed(message,100);
//                if(!isWatchWrongTopic) {
//                    tvCurrentNum.setText("(" + (pageIndex + 1));
//                }
//                break;
//            default:
//                break;
//        }
//    }
//
//    /**
//     * 收藏和取消收藏
//     *
//     * @param collectType 1:收藏试题2:取消收藏试题
//     */
//    private void doPostCollect(final int collectType) {
//        ExamFragment examFragment = (ExamFragment) examFragmentAdapter.getItem(pageIndex);
//        ExerciseBean exerciseBean = examFragment.getExerciseBean();
//        int childId = shuShanApplication.getCurrentChildId();
//
//        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.TOPIC_COLLECT);
//        UrlParse paramParse = new UrlCommParse(this)
//                .putValue("child_id", childId)
//                .putValue("exercise_id", exerciseBean.id)
//                .putValue("subject_id", exerciseBean.subject_id)
//                .putValue("exercises_type", examType)
//                .putValue("type", collectType + "");
//
//        showWaitDialog();
//        NetHelper.create()
//                .url(urlParse.toStringOnlyHeader())
//                .param(paramParse.toStringOnlyParam())
//                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
//                    @Override
//                    protected void onCommon() {
//                        dismissWaitDialog();
//                    }
//
//                    @Override
//                    protected void onSuccess(String data) {
//                        dealCollect();
//                    }
//
//                    @Override
//                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
//                        showNetError(netRetBean);
//                    }
//                });
//    }
//
//    private void dealCollect() {
//        ExamFragment examFragment = (ExamFragment) examFragmentAdapter.getItem(pageIndex);
//        ExerciseBean exerciseBean = examFragment.getExerciseBean();
//
//        if (exerciseBean.child_collect == 1) {
//            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
//            exerciseBean.child_collect = 0;
//        } else {
//            examButton.setBackgroundResource(R.drawable.exam_title_collected);
//            exerciseBean.child_collect = 1;
//        }
//
//    }
//
//    private void showCollect() {
//        ExamFragment examFragment = (ExamFragment) examFragmentAdapter.getItem(pageIndex);
//        ExerciseBean exerciseBean = examFragment.getExerciseBean();
//
//        if (exerciseBean.child_collect == 1) {
//            examButton.setBackgroundResource(R.drawable.exam_title_collected);
//        } else {
//            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
//        }
//    }
//
//    private void getExamPaper() {
//        if (rewardTimeBean != null) {
//            examType = rewardTimeBean.practice_type;
//        } else if (rewardToyBean != null) {
//            examType = rewardToyBean.practice_type;
//        }
//
//        Log.i(TAG, "examType=" + examType);
//
//        if (fromResultType == 0) {
//            examPaperBean = (PaperBean) Session.getSession().get("examPaperBean");
//            setRepeatExam(true, examPaperBean);
//        } else if (fromResultType == 1) {
//            examPaperBean = (PaperBean) Session.getSession().get("examPaperBean");
//            setRepeatExam(false, examPaperBean);
//        } else {
//            switch (examType) {
//                case Constants.TYPE_SYNC_EXERCISE:
//                    getTBExamPaper();
//                    break;
//                case Constants.TYPE_SMART_EXERCISE:
//                    getSmartExamPaper();
//                    break;
//                case Constants.TYPE_LEARN_BY_DO:
//                    getLearnByExamPaper();
//                    break;
//                case Constants.TYPE_KEY_POINT_EXERCISE:
//                case Constants.TYPE_DIFFICULT_POINT_EXERCISE:
//                case Constants.TYPE_EASY_WRONG_EXERCISE:
//                case Constants.TYPE_SPECIAL_TOPIC_EXERCISE:
//                    getSpecialExamPaper(examType);
//                    break;
//                default:
//                    break;
//            }
//
//        }
//    }
//
//    private void setRepeatExam(boolean hasClear, PaperBean examPaperBean) {
//        if (examPaperBean == null) {
//            return;
//        }
//
//        paperId = examPaperBean.id;
//
//        if (hasClear) {
////待解            ToolUtils.clearRecord(examPaperBean);
//        } else {
//        }
//
//        setData(!hasClear, examPaperBean);
//    }
//
//    private void getTBExamPaper() {
//        int childId = shuShanApplication.getCurrentChildId();
//
//        showWaitDialog();
//
//        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_TB_PAPER);
//        UrlParse paramParse = new UrlCommParse(this)
//                .putValue("child_id", childId);
//
//        NetHelper.create()
//                .url(urlParse.toStringOnlyHeader())
//                .param(paramParse.toStringOnlyParam())
//                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<PaperBean>() {
//                    @Override
//                    protected void onCommon() {
//                        dismissWaitDialog();
//                    }
//
//                    @Override
//                    protected void onSuccess(PaperBean tbPaperBean) {
//                        examPaperBean = tbPaperBean;
//                        paperId = tbPaperBean.id;
//
//                        setData(false, tbPaperBean);
//                    }
//
//                    @Override
//                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
//                        Log.i(TAG, "onSuccess netRetBean=" + netRetBean.toString());
//
//                        showNetError(netRetBean);
//                    }
//                });
//    }
//
//
//    private void getSmartExamPaper() {
//        int childId = shuShanApplication.getCurrentChildId();
//
//        showWaitDialog();
//
//        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_ZN_PAPER);
//        UrlParse paramParse = new UrlCommParse(this)
//                .putValue("child_id", childId);
//
//        NetHelper.create()
//                .url(urlParse.toStringOnlyHeader())
//                .param(paramParse.toStringOnlyParam())
//                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<PaperBean>() {
//                    @Override
//                    protected void onCommon() {
//                        dismissWaitDialog();
//                    }
//
//                    @Override
//                    protected void onSuccess(PaperBean tbPaperBean) {
//                        examPaperBean = tbPaperBean;
//                        paperId = tbPaperBean.id;
//
//                        setData(false, tbPaperBean);
//                    }
//
//                    @Override
//                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
//
//                        showNetError(netRetBean);
//                    }
//                });
//    }
//
//    private void getLearnByExamPaper() {
//        int childId = shuShanApplication.getCurrentChildId();
//
//        showWaitDialog();
//
//        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_LEARN_BY_PAPER);
//        UrlParse paramParse = new UrlCommParse(this)
//                .putValue("child_id", childId)
//                .putValue("subject_id", subjectId)
//                .putValue("video_id", videoId);
//
//        NetHelper.create()
//                .url(urlParse.toStringOnlyHeader())
//                .param(paramParse.toStringOnlyParam())
//                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
//                    @Override
//                    protected void onCommon() {
//                        dismissWaitDialog();
//                    }
//
//                    @Override
//                    protected void onSuccess(String data) {
////待解                        examPaperBean = StringTools.getExerciseJsonBean(examType, data);
//                        paperId = examPaperBean.id;
//
//                        setData(false, examPaperBean);
//                    }
//
//                    @Override
//                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
//
//                        showNetError(netRetBean);
//                    }
//                });
//    }
//
//    private void getSpecialExamPaper(final int examType) {
//        int childId = shuShanApplication.getCurrentChildId();
//
//        showWaitDialog();
//
//        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_ZT_PAPER);
//        UrlParse paramParse = new UrlCommParse(this)
//                .putValue("child_id", childId)
//                .putValue("practice_type", examType)
//                .putValue("special_id", specialId);
//
//        NetHelper.create()
//                .url(urlParse.toStringOnlyHeader())
//                .param(paramParse.toStringOnlyParam())
//                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
//                    @Override
//                    protected void onCommon() {
//                        dismissWaitDialog();
//                    }
//
//                    @Override
//                    protected void onSuccess(String data) {
////待解                        examPaperBean = StringTools.getExerciseJsonBean(examType, data);
//                        paperId = examPaperBean.id;
//
//                        setData(false, examPaperBean);
//                    }
//
//                    @Override
//                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
//
//                        showNetError(netRetBean);
//                    }
//                });
//    }
//
//    private void setData(boolean isOnlyDisplay, PaperBean tbPaperBean) {
//        if (tbPaperBean == null) {
//            Log.e(TAG, "tbPaperBean == null");
//            return;
//        }
//
//        List<Fragment> fragments = new ArrayList<Fragment>();
//
//        List<ExerciseBean> chineseExerciseList = tbPaperBean.getChineseExerciseList();
//        int size1 = chineseExerciseList.size();
//        int chineseWrongSize = 0;//语文错题数
//        for (int i = 0; i < chineseExerciseList.size(); i++) {
//            ExerciseBean exerciseBean = chineseExerciseList.get(i);
//            if(isWatchWrongTopic) {
//                List<ExerciseOptionBean> optionList = exerciseBean.getOptionList();
//                if(isFromRecord){
//                    if(isExamWrong(optionList,exerciseBean.my_answer_id)){
//                        chineseWrongSize++;
//                        ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, chineseWrongSize, exerciseBean);
//                        examFragment.setOnAnswerSelectListener(this);
//                        fragments.add(examFragment);
//                    }
//                }else{
////待解                   if (ToolUtils.isExamWrong(optionList)) {
////                        chineseWrongSize++;
////                        ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, chineseWrongSize, exerciseBean);
////                        examFragment.setOnAnswerSelectListener(this);
////                        fragments.add(examFragment);
////                    }
//                }
//            }else {
//                ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
//                examFragment.setOnAnswerSelectListener(this);
//                fragments.add(examFragment);
//            }
//        }
//
//        List<ExerciseBean> mathExerciseList = tbPaperBean.getMathExerciseList();
//        int size2 = mathExerciseList.size();
//        int mathWrongSize = 0;//数学错题数
//        for (int i = 0; i < mathExerciseList.size(); i++) {
//            ExerciseBean exerciseBean = mathExerciseList.get(i);
//            if(isWatchWrongTopic) {
//                List<ExerciseOptionBean> optionList = exerciseBean.getOptionList();
//                if(isFromRecord){
//                    if(isExamWrong(optionList,exerciseBean.my_answer_id)){
//                        mathWrongSize++;
//                        ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, chineseWrongSize + mathWrongSize, exerciseBean);
//                        examFragment.setOnAnswerSelectListener(this);
//                        fragments.add(examFragment);
//                    }
//                }else {
////待解                    if (ToolUtils.isExamWrong(optionList)) {
////                        mathWrongSize++;
////                        ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, chineseWrongSize + mathWrongSize, exerciseBean);
////                        examFragment.setOnAnswerSelectListener(this);
////                        fragments.add(examFragment);
////                    }
//                }
//            }else {
//                ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, size1 + i,exerciseBean);
//                examFragment.setOnAnswerSelectListener(this);
//                fragments.add(examFragment);
//            }
//        }
//
//        List<ExerciseBean> englishExerciseList = tbPaperBean.getEnglishExerciseList();
//        int size3 = englishExerciseList.size();
//        int englishWrongSize = 0;//英语错题数
//        for (int i = 0; i < englishExerciseList.size(); i++) {
//            ExerciseBean exerciseBean = englishExerciseList.get(i);
//            if(isWatchWrongTopic) {
//                List<ExerciseOptionBean> optionList = exerciseBean.getOptionList();
//                if(isFromRecord){
//                    if(isExamWrong(optionList,exerciseBean.my_answer_id)){
//                        englishWrongSize++;
//                        ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, chineseWrongSize + mathWrongSize + englishWrongSize,exerciseBean);
//                        examFragment.setOnAnswerSelectListener(this);
//                        fragments.add(examFragment);
//                    }
//                }else {
////待解                    if (ToolUtils.isExamWrong(optionList)) {
////                        englishWrongSize++;
////                        ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, chineseWrongSize + mathWrongSize + englishWrongSize, exerciseBean);
////                        examFragment.setOnAnswerSelectListener(this);
////                        fragments.add(examFragment);
////                    }
//                }
//            }else {
//                ExamFragment examFragment = ExamFragment.newInstance(isOnlyDisplay, size1 + size2 + i, exerciseBean);
//                examFragment.setOnAnswerSelectListener(this);
//                fragments.add(examFragment);
//            }
//        }
//        if(isWatchWrongTopic) {
//            tvTopicTotalNum.setText("/" + (chineseWrongSize + mathWrongSize + englishWrongSize)+")");
//        }else{
//            tvTopicTotalNum.setText("/" + (size1 + size2 + size3)+")");
//            topicTotalNum = size1+size2+size3;
//            Log.i(TAG,"topicTotalNum = "+topicTotalNum);
//        }
//        examFragmentAdapter = new ExamFragmentAdapter(this, getSupportFragmentManager(), fragments);
//        viewPager.setAdapter(examFragmentAdapter);
//    }
//
//    private boolean isExamWrong(List<ExerciseOptionBean> optionList, int answerId) {
//        if(optionList == null || optionList.size() == 0){
//            return false;
//        }
//
//        for(ExerciseOptionBean optionBean : optionList){
//            if(optionBean.id == answerId && optionBean.option_result == 0){
//                return true;
//            }
//        }
//        return false;
//    }
//
//    //返回需要回答的题目序号
//    public static int getShouldAnswerIndex(){
//        return currentTopicIndex + 1;
//    }
//
//    //返回是否跳题 true 是跳题，false 非跳题
//    public static boolean isSkipTopic(){
//        return pageIndex > currentTopicIndex+1;
//    }
//
//    @Override
//    public boolean onAnswerSelect(int examIndex, boolean isRight) {
//        Log.i(TAG, "examIndex=" + examIndex+" currentTopicIndex= "+currentTopicIndex + " isRight=" + isRight);
//        if(!Constants.isForEditors) {
//            if (examIndex - currentTopicIndex > 1) {
//                showSkipTopicDialog(currentTopicIndex + 1);
//                return false;
//            }
//            currentTopicIndex = examIndex;
//        }
//        btnNextTopic.setEnabled(true);
//        if (isRight) {
//            rightNum++;
//        } else {
//            wrongNum++;
//        }
//
//        if ((rightNum + wrongNum) == examFragmentAdapter.getCount()) {
//            answeredReceiver = new AnsweredReceiver();
//            IntentFilter filter = new IntentFilter(Constants.ANSWERED_RECEIVER_ACTION);
//            LocalBroadcastManager.getInstance(this).registerReceiver(answeredReceiver,filter);
//        } else {
//            if (isRight) {
//                soundPool.play(soundIdMap.get(0), 1, 1, 1, 0, 1);
//                if(rightAnimation.isRunning()){
//                    rightAnimation.stop();
//                }
//                rightAnimation.start();
//            } else {
//                soundPool.play(soundIdMap.get(1), 1, 1, 1, 0, 1);
//                if(wrongAnimation.isRunning()){
//                    wrongAnimation.stop();
//                }
//                wrongAnimation.start();
//            }
//        }
//        return true;
//    }
//
//    private class JumpToShouldAnswerIndexReceiver extends BroadcastReceiver{
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            Message msg = scrollHandler.obtainMessage(0);
//            msg.arg1 = intent.getIntExtra("shouldAnswerIndex",0);
//            scrollHandler.sendMessage(msg);
//        }
//    }
//
//    private class AnsweredReceiver extends BroadcastReceiver{
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if(!Constants.isForEditors) {
//                postPaperRecord(examPaperBean);
//            }
//                LocalBroadcastManager.getInstance(context).unregisterReceiver(answeredReceiver);
//        }
//    }
//
//    /**
//     *  发现跳题答题时弹出
//     * @param shouldAnswerIndex 应答题的序号
//     */
//    private void showSkipTopicDialog(final int shouldAnswerIndex) {
//        skipTopicDialog = new CustomDialog.Builder(this)
//                .setTitle("温馨提示")
//                .setMessage("第"+(shouldAnswerIndex+1)+"题还没有作答")
//                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                })
//                .setPositiveButton("返回第"+(shouldAnswerIndex+1)+"题", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//
//                        Message msg = scrollHandler.obtainMessage(0);
//                        msg.arg1 = shouldAnswerIndex;
//                        scrollHandler.sendMessage(msg);
//
//                    }
//                })
//                .create();
//        skipTopicDialog.show();
//    }
//
//    public void postPaperRecord(PaperBean tbPaperBean) {
//        int childId = shuShanApplication.getCurrentChildId();
//        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.PAPER_ANSWER_RECORD);
//        UrlParse paramParse = new UrlCommParse(this)
//                .putValue("child_id", childId)
//                .putValue("paper_id", examPaperBean.id + "")
//                .putValue("answer", getAnswerArray(tbPaperBean))
//                .putValue("repeat", (fromResultType == 0) ? "1" : "2")
//                .putValue("time_consuming", examTime + "")
//                .putValue("exercises_type", examType + "")
//                .putValue("video_id", (examType == 3) ? videoId + "" : "0")
//                .putValue("video_id", (examType > 3) ? specialId + "" : "0");
//
//        showWaitDialog();
//        NetHelper.create()
//                .url(urlParse.toStringOnlyHeader())
//                .param(paramParse.toStringOnlyParam())
//                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<ExerciseResultBean>() {
//
//                    @Override
//                    protected void onCommon() {
//                        dismissWaitDialog();
//                    }
//
//                    @Override
//                    protected void onSuccess(ExerciseResultBean exerciseResultBean) {
//                        cannotBackstage = false;
//
//                        onBackAction();
//
//                        gotoScoreResult(exerciseResultBean);
//                    }
//
//                    @Override
//                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
//                        showNetError(netRetBean);
//                    }
//                });
//    }
//
//    private JSONObject getAnswerJson(ExerciseBean exerciseBean) {
//        if (exerciseBean == null) {
//            return null;
//        }
//
//        List<ExerciseOptionBean> optionLis = exerciseBean.getOptionList();
//        ExerciseOptionBean selectOptionBean = null;
//        int rightOptionId = 0;
//        for (ExerciseOptionBean optionBean : optionLis) {
//            if (optionBean.getAnswerIndex() >= 0) {
//                selectOptionBean = optionBean;
//            }
//
//            if (optionBean.option_result == 1) {
//                rightOptionId = optionBean.id;
//            }
//        }
//
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("id", exerciseBean.id);
//            jsonObject.put("exercises_type", "SINGLE");
//            jsonObject.put("outline_detail_id", exerciseBean.outline_detail_id);
//            jsonObject.put("score", exerciseBean.score);
//            jsonObject.put("right_option", rightOptionId);
//            jsonObject.put("subject_id", exerciseBean.subject_id);
//            jsonObject.put("outline_id", exerciseBean.outline_id);
//            if (selectOptionBean != null) {
//                jsonObject.put("option_result", selectOptionBean.option_result);
//                jsonObject.put("my_option", selectOptionBean.id);
//            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        return jsonObject;
//
//    }
//
//    private String getAnswerArray(PaperBean examPaperBean) {
//        if (examPaperBean == null) {
//            return "";
//        }
//
//        JSONArray answerArray = new JSONArray();
//
//        List<ExerciseBean> chineseExerciseList = examPaperBean.getChineseExerciseList();
//        if (chineseExerciseList != null) {
//            for (ExerciseBean exerciseBean : chineseExerciseList) {
//                answerArray.put(getAnswerJson(exerciseBean));
//            }
//        }
//
//        List<ExerciseBean> mathExerciseList = examPaperBean.getMathExerciseList();
//        if (mathExerciseList != null) {
//            for (ExerciseBean exerciseBean : mathExerciseList) {
//                answerArray.put(getAnswerJson(exerciseBean));
//            }
//        }
//
//        List<ExerciseBean> englishExerciseList = examPaperBean.getEnglishExerciseList();
//        if (englishExerciseList != null) {
//            for (ExerciseBean exerciseBean : englishExerciseList) {
//                answerArray.put(getAnswerJson(exerciseBean));
//            }
//        }
//
//        return answerArray.toString();
//    }
//
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            onTitleBack();
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
//
//    private void gotoScoreResult(ExerciseResultBean exerciseResultBean) {
//        if (exerciseResultBean == null) {
//            showToast("服务端数据返回为空");
//            return;
//        }
//
//        Session.getSession().put("exerciseResultBean", exerciseResultBean);
//        Session.getSession().put("examPaperBean", examPaperBean);
//
//        Session.getSession().put("rewardTimeBean", rewardTimeBean);
//        Session.getSession().put("rewardToyBean", rewardToyBean);
//
//        Intent intent = new Intent(ExamActivity.this, ExamScoreActivity.class);
//        intent.putExtra("awardType", awardType);
//        intent.putExtra("paperId", paperId);
//        intent.putExtra("examTime", examTime);
//        intent.putExtra("examType", examType);
//        startActivityAllow(intent);
//    }
//
//    private void doRepeatExam() {
//        awardType = getIntent().getIntExtra("awardType", 1);
//
//        int scorePaperId = getIntent().getIntExtra("paperId", 0);
//        if (scorePaperId > 0) {
//            paperId = scorePaperId;
//        }
//
//        RewardTimeBean scoreRewardTimeBean = (RewardTimeBean) Session.getSession().get("rewardTimeBean");
//        if (scoreRewardTimeBean != null) {
//            rewardTimeBean = scoreRewardTimeBean;
//        }
//        RewardToyBean scoreRewardToyBean = (RewardToyBean) Session.getSession().get("rewardToyBean");
//        if (scoreRewardToyBean != null) {
//            rewardToyBean = scoreRewardToyBean;
//        }
//
//        PaperBean scorePaperBean = (PaperBean) Session.getSession().get("examPaperBean");
//        if (scorePaperBean != null) {
//            examPaperBean = scorePaperBean;
//        }
//
//        setRepeatExam(true, examPaperBean);
//
//    }
//
//    private void showNoBackWarnDialog() {
//        new CustomDialog.Builder(this)
//                .setTitle("温馨提示")
//                .setMessage("答题期间，没有答完题目，数据尚未上报，不建议退出，是否退出？")
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//
//                        finish();
//                    }
//                })
//                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                })
//                .create().show();
//    }

}
